#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from typing import List
from app.types.apiproto.studentscore_protp import StudentStatisticOut, StudentScoreModel
from app.dao.student_score_dao import StudentScoreDAO
from app.service.studentscoresvc.student_score_svc import (
    StudentScoreService,
)
from io import BytesIO
from fastapi import Query, UploadFile, File, APIRouter, HTTPException
import pandas as pd
from app.utils.log import logger

router = APIRouter(prefix="/gpa", tags=["gpa相关操作"])


@router.post("/excel")
async def upload_excel(file: UploadFile = File(...)):
    if file is None:
        raise HTTPException(status_code=400, detail="请上传 Excel 文件")

    try:
        contents = await file.read()
        df = pd.read_excel(BytesIO(contents))
        df = df.where(pd.notnull(df), None)

    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Excel 读取失败: {str(e)}")

    if df.empty:
        raise HTTPException(status_code=400, detail="Excel 表为空，请检查内容")

    records = df.to_dict(orient="records")
    StudentScoreDAO.delete_all()  # 清空旧数据
    StudentScoreService.import_scores(records)

    return {"status": "success", "message": f"成功导入 {len(records)} 条记录"}


@router.get("/major-stat")
def get_major_statistics():
    return StudentScoreDAO.count_students_by_major()


@router.get("/detail/{student_id}", response_model=List[StudentScoreModel])
async def get_student_scores(student_id: str):
    scores = StudentScoreService.get_scores_for_student(student_id)
    outs = []
    for score in scores:
        if score.score is None:
            logger.info(
                f"{score.student_id} {score.name} {score.course_name} {score.score}"
            )
            score.score = 0
        if score.class_name is None:
            score.class_name = "无"
        outs.append(StudentScoreModel.model_validate(score))

    if not scores:
        raise HTTPException(status_code=404, detail="No scores found for this student.")
    return outs


@router.get("/by-major")
def get_student_statistics_by_major(major: str = Query(..., description="专业名称")):
    """
    根据专业名称查询该专业下学生统计列表
    """
    return StudentScoreService.get_statistics_by_major(major)


@router.get("/by-sid")
def get_student_statistics_by_major(student_id: str = Query(..., description="学号")):
    """
    根据专业名称查询该专业下学生统计列表
    """
    return StudentScoreService.get_statistics_by_sid(student_id)
